import { t } from 'i18next'
import createVanilla from 'zustand/vanilla'
import create from 'zustand'
import { MixCometd, ListTranslator, PlanEntity, TerMode } from './translator'
import { differenceBy } from 'lodash-es'
import Alert from '@/components/Alert'
import { changeMixMembersEntity, FetchMixResponseEntity, StartParamsMixEntity } from '@/api/manager/mix/interface'
import { fetchChangeMixInfo, fetchChangeMixMembers, fetchUpdateMtMute } from '@/api/manager/mix'
import { useMccStore } from '../../store'
import { Mt, MtEntity, revert_mt } from '@/api/manager/mt'
import { useManagerStore } from '../main/manager/store'
import { useParamsStore } from '../main/store'
import { useTableAllStore } from '../main/table/all/store'
import { getItemByMtKey } from '../main/table/all/utils'

type StateStore = {
	/**哑音 */
	mute: number
	/**预案列表 */
	planOptions: PlanEntity
	/**预案选中的值 */
	planValue: string
	/**预案名称 */
	preName: string
	/**轮询状态0 空闲  1轮询中  2暂停*/
	state: number
	/**显示的轮询终端 */
	list: Array<TerMode>
	/**轮询终端*/
	members: Array<Partial<MtEntity>>
	/**轮询终端数据备份*/
	membersDataBackup: Array<MtEntity>
	/**保存预案的模态框 */
	isSavePlanOpen: boolean
	/**输入的预案名称 */
	name: string
	/**是否处于编辑状态*/
	isEdit: boolean
	/**当前的轮询模式(3可能和语音激励相关)*/
	mode: 1 | 2 | 3
	/**智能混音列表 */
	intelligent_mix_list: Array<TerMode>
	/**定制混音列表 */
	custom_mix_list: Array<TerMode>
	radioFlag: boolean
	/**1为正在切换预案 */
	change_plan: 0 | 1
	/**此字段是为了左侧表格直接操作添加到混音 操作有添加到定制混音*/
	is_call_back: boolean
	is_call_back_mt: Array<MtEntity & { isMt: boolean }>
	_start: string
	_changes: string[]
}
type IStore = StateStore & {
	update: (d: Partial<StateStore>) => void
	reset: () => void
	updateMuteForMix: (_updates: Array<MtEntity>) => void
	addList: (_list: MtEntity[]) => void
	/**批量新增终端 */
	batchAddList: (_list: MtEntity[]) => void
	removeMt: (mtKey: string) => void
	/**删除退会终端 */
	removeLi: (mtKeys: string[]) => void
	/**删除批量终端 */
	removeBatchMt: () => void
	updateList: (updateList: MtEntity[]) => void
	/**获取查询参数*/
	getPara: () => StartParamsMixEntity
	/**获取保存和更新预案数据 */
	getPlanPara: (flag: boolean) => StartParamsMixEntity
	/**重置混音信息 */
	resetMix: () => void
	/**获取混音的全部哑音状态*/
	getMixMute: (_data: Array<MtEntity>) => [boolean, Array<MtEntity>]
	/**取消/设置单个哑音状态 1-设置静音/哑音; 0-取消静音/哑音;*/
	muteSingleOption: (mt_key: string, value: number) => void
	/**批量操作*/
	muteOption: (_flag: number) => void
	/**切换混音类型 */
	changeMode: (_mode: number) => void
	/**改变混音成员 */
	changeMix: () => void
	msgHandle: (_data: MixCometd) => void
	/**从左侧列表添加数据 */
	render: (_data: Array<MtEntity & { isMt: boolean }>) => void
	toggleClick: (mtKey: string) => void
	toggleCtrl: (mtKey: string) => void
	toggleShift: (mtKey: string) => void
	addMixMembers: (_data: MtEntity[], call_back: () => void) => {}
	/**重置混音 */
	renderPreMix: (_data: FetchMixResponseEntity | undefined) => void
}
const initialState: StateStore = {
	change_plan: 0,
	planOptions: [{ label: t('不使用预案'), value: '0' }],
	mute: 0,
	isEdit: false,
	planValue: '',
	state: 1,
	membersDataBackup: [],
	// isAudio: 0,
	list: [],
	members: [],
	preName: '',
	isSavePlanOpen: false,
	mode: 1,
	radioFlag: false,
	name: '',
	intelligent_mix_list: [],
	custom_mix_list: [],
	is_call_back: false,
	is_call_back_mt: [],
	_start: '',
	_changes: [],
}
export const store = createVanilla<IStore>((set, get) => ({
	...initialState,
	update: (d) => set({ ...d }),
	reset: () => set(initialState),
	updateMuteForMix: (_updates) => {
		const { custom_mix_list, intelligent_mix_list, mode } = get()
		const list = mode === 1 ? intelligent_mix_list : custom_mix_list
		for (const mt of _updates) {
			for (const item of list) {
				if (item.mtKey === mt.mt_key) {
					item.mcc = new Mt(mt)
				}
			}
		}
		if (mode === 1) {
			set({ intelligent_mix_list: [...list] })
		} else {
			set({ custom_mix_list: [...list] })
			/**存在非哑音 */
			const _mute_flag = custom_mix_list.findIndex((item) => {
				return !item.mcc.status.isMute
			})
			set({ mute: _mute_flag === -1 ? 1 : 0 })
		}
	},
	changeMix: async () => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const { state, mode, custom_mix_list, preName } = get()
		if (!state) return
		if (mode === 2) {
			let members: Array<Partial<changeMixMembersEntity>> = custom_mix_list.map((item) => {
				const data = item.mcc
				return {
					account_type: Number(data.accountType ? data.accountType : 0),
					mt_id: data.mtid ? data.mtid : '',
					account: data.account ? data.account : '',
					mt_key: data.mtKey ? data.mtKey : '',
					moid: data.moid ? data.moid : '',
					e164: data.e164 ? data.e164 : '',
					conf_e164: data.confE164 ? data.confE164 : '',
				}
			})
			const params = {
				id: '',
				mode,
				name: preName,
				members: members,
			}
			const res = await fetchChangeMixInfo(meetingMoid, params)
			if (!res.success) {
				Alert(t('修改混音失败'))
			} else if (res.description === 'same') {
				//保持原样
			}
		}
	},
	addMixMembers: async (members, callBack) => {
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		let _members: Array<Partial<changeMixMembersEntity>> = members.map((item) => {
			const data = item
			return {
				account_type: Number(data.account_type ? data.account_type : 0),
				mt_id: data.mt_id ? data.mt_id : '',
				account: data.account ? data.account : '',
				mt_key: data.mt_key ? data.mt_key : '',
				moid: data.moid ? data.moid : '',
				e164: data.e164 ? data.e164 : '',
				conf_e164: data.conf_e164 ? data.conf_e164 : '',
			}
		})
		const res = await fetchChangeMixMembers(meetingMoid, _members)
		if (res.success) {
			Alert(t('修改混音成功'))
			callBack && callBack()
		} else {
			Alert(res.description || t('修改混音失败'))
		}
	},
	/**1-设置静音/哑音; 0-取消静音/哑音;*/
	muteSingleOption: async (mt_key, option) => {
		const { custom_mix_list, intelligent_mix_list, mode } = get()
		const list = mode === 1 ? intelligent_mix_list : custom_mix_list
		const _item = list.find((l) => l.mtKey === mt_key)
		/**设置单个终端哑音 如果离线终端就不发了,保证有mtid*/
		if (_item) {
			if (_item.mcc.status.isOnline) {
				const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
				const { e164, mt_id, mt_ip, name, conf_e164, account_type, account, protocol } = revert_mt(_item.mcc)
				const parsms = {
					value: option /**1-设置静音/哑音; 0-取消静音/哑音;*/,
					mts: [
						{
							e164: e164,
							mt_id: mt_id,
							mt_ip: mt_ip,
							name,
							conf_e164,
							account,
							protocol,
							account_type: account_type,
						},
					],
				}
				const success = await fetchUpdateMtMute(meetingMoid, parsms)
				let text = option === 0 ? t('取消哑音失败') : t('设置哑音失败')
				!success && Alert(text)
			}
		}
	},
	muteOption: async (_flag: number) => {
		set({ mute: _flag })
		/**1-设置静音/哑音; 0-取消静音/哑音;*/
		const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
		const { custom_mix_list } = get()
		const mts = custom_mix_list
			.map((item) => {
				const { e164, mt_id, mt_ip, name, conf_e164, account_type, account, protocol, online } = revert_mt(
					item.mcc as Mt
				)
				if (online) {
					return {
						e164: e164,
						mt_id: mt_id,
						mt_ip: mt_ip,
						name,
						conf_e164,
						account,
						protocol,
						account_type: account_type,
					}
				}
				return null
			})
			.filter(Boolean)
		const parsms = {
			value: _flag,
			mts: mts,
		}
		const success = await fetchUpdateMtMute(meetingMoid, parsms)
		!success && set({ mute: 0 })
		!success && Alert(t('设置哑音失败'))
	},
	getMixMute: (_data: Array<MtEntity>) => {
		let _flag = true
		const tree = useTableAllStore.getState().tree
		_data.forEach((item) => {
			const _mt_id = item.mt_id
			const _item = getItemByMtKey(tree, _mt_id)
			if (_mt_id && _item) {
				let mute: 0 | 1 = _item.mcc.status.isMute ? 1 : 0
				item.mute = mute
				//判断是否全部哑音
				if (!mute) {
					_flag = false
				}
			}
		})
		return [_flag, _data]
	},
	/**重置混音界面*/
	resetMix: function () {
		set({
			state: 0,
			mode: 1,
			intelligent_mix_list: [],
			custom_mix_list: [],
			preName: '',
		})
	},
	/**切换混音类型 */
	changeMode: (_mode: number) => {
		if (_mode === 1) {
			//智能混音
			useParamsStore.getState().hideActionButton()
			set({
				mode: 1,
				intelligent_mix_list: [],
				custom_mix_list: [],
			})
		} else {
			//定制混音
			useParamsStore.getState().showActionButton()
			set({
				mode: 2,
				intelligent_mix_list: [],
				custom_mix_list: [],
			})
		}
	},
	/**获取参数*/
	getPara: () => {
		const { mode, preName, custom_mix_list, planValue } = get()
		let members = custom_mix_list.map((item) => {
			const data = item.mcc
			return {
				account_type: Number(data.accountType ? data.accountType : 0),
				mt_id: data.mtid ? data.mtid : '',
				account: data.account ? data.account : '',
				mt_key: data.mtKey ? data.mtKey : '',
				e164: data.e164 ? data.e164 : '',
				conf_e164: data.confE164 ? data.confE164 : '',
				mt_ip: data.mtIp ? data.mtIp : '',
				name: data.name ? data.name : '',
			}
		})
		return {
			/**混音预案id，跨级建云会议机房创会需要，不对外*/
			id: planValue === '0' ? '' : planValue,
			/**混音模式1-智能混音;2-定制混音;*/
			mode: mode,
			/**预案名称*/
			name: preName,
			/**混音终端成员*/
			members: mode === 1 ? [] : members,
		}
	},
	/**
	 *
	 * @param isUpdate 是否是更新预案
	 * @returns
	 */
	getPlanPara: (isUpdate: boolean) => {
		const { custom_mix_list, mode, preName, name, planValue } = get()
		let _members: Array<any> = []
		if (mode === 2) {
			_members = custom_mix_list.map((item) => {
				const data = item.mcc
				return {
					account_type: Number(data.accountType ? data.accountType : 0),
					mt_id: data.mtid ? data.mtid : '',
					account: data.account ? data.account : '',
					mt_key: data.mtKey ? data.mtKey : '',
					moid: data.moid ? data.moid : '',
					e164: data.e164 ? data.e164 : '',
					conf_e164: data.confE164 ? data.confE164 : '',
				}
			})
		}
		const _name = isUpdate ? preName : name
		const _id = isUpdate ? planValue : ''
		return {
			mode: mode,
			id: _id,
			members: _members, //混音成员
			name: _name, // 预案名称
		}
	},
	/**新增终端*/
	addList: (addList) => {
		const { custom_mix_list } = get()
		let mts = ListTranslator(addList)
		const insertList = differenceBy(mts, custom_mix_list, (x) => x.mtKey)
		set({
			custom_mix_list: [
				...custom_mix_list.slice(0, custom_mix_list.length),
				...insertList,
				...custom_mix_list.slice(custom_mix_list.length),
			],
		})
	},
	/**批量新增终端*/
	batchAddList: (mtToAdd) => {
		let _mtToAdd = mtToAdd.filter((x) => x.online)
		if (mtToAdd.length > _mtToAdd.length) {
			Alert(t('离线终端不能加入定制混音'))
		}
		const { custom_mix_list, changeMix } = get()
		let mts = ListTranslator(_mtToAdd)
		const insertList = differenceBy(mts, custom_mix_list, (x) => x.mtKey)
		set({
			custom_mix_list: [
				...custom_mix_list.slice(0, custom_mix_list.length),
				...insertList,
				...custom_mix_list.slice(custom_mix_list.length),
			],
		})
		changeMix()
	},
	/**移除终端*/
	removeMt: (mtKey) => {
		const { state, custom_mix_list, mode, changeMix } = get()
		const unRemove = custom_mix_list.filter((l) => l.mtKey !== mtKey)
		const speaker = useManagerStore.getState().speaker
		if (mtKey === speaker?.mtKey && state === 1) {
			Alert(t('发言人必须参加混音 '))
			return false
		} else {
			if (state) {
				if (unRemove.length === 0 && mode === 2) {
					Alert(t('定制混音时混音列表不能为空'))
					return false
				}
			}
			set({ custom_mix_list: unRemove })
			changeMix()
		}
	},
	/**移除批量终端*/
	removeBatchMt: () => {
		const { state, custom_mix_list, mode, changeMix } = get()
		const speaker = useManagerStore.getState().speaker
		const unCheckedList = custom_mix_list.filter((l) => !l.status.checked)
		const checkedList = custom_mix_list.filter((l) => l.status.checked)
		const flag = checkedList.findIndex((item) => {
			return item.mtKey === speaker?.mtKey
		})
		if (state === 1 && flag !== -1) {
			Alert(t('发言人必须参加混音 '))
			return false
		}
		if (state === 1 && unCheckedList.length === 0 && mode === 2) {
			Alert(t('定制混音时混音列表不能为空'))
			return false
		}
		set({ custom_mix_list: unCheckedList })
		changeMix()
	},
	/**删除退会终端 */
	removeLi: (mtKeys) => {
		const { custom_mix_list } = get()
		const unRemove = custom_mix_list.filter((l) => !mtKeys.includes(l.mtKey))
		set({ custom_mix_list: unRemove })
	},
	/**更新终端*/
	updateList: (updateList = []) => {
		let _updates = updateList.filter((mt) => mt.conf_level === 2)
		const newList = get().list
		for (const mt of _updates) {
			for (const item of newList) {
				if (item.mtKey === mt.mt_key) {
					item.mcc = new Mt(mt)
				}
			}
		}
		set({ list: [...newList] })
	},
	renderPreMix: (source: FetchMixResponseEntity | undefined) => {
		const { resetMix, getMixMute } = get()
		if (!source) {
			/**重置混音 */
			resetMix()
			return false
		} else {
			const { state, mode, name, members } = source
			set({
				state: state || 0,
				preName: name,
			})
			if (state === 0) {
				/**混音未开或者是语音激励 */
				// resetMix() //保留原始数据
			} else {
				//业务出现过推member为null的消息的问题，前端做一层保护
				let newMembers = members.filter((item) => item)
				/**混音开启 */
				if (mode === 1 /**智能 */) {
					useParamsStore.getState().hideActionButton()
					set({
						custom_mix_list: [],
						intelligent_mix_list: ListTranslator(newMembers || []),
					})
				} else if (mode === 2 /**定制 */) {
					useParamsStore.getState().showActionButton()
					/**true 代表全部哑音  false代表部分哑音 */
					const [_all_mute, _members] = getMixMute(newMembers)
					set({
						mode: 2,
						mute: Number(_all_mute),
						custom_mix_list: ListTranslator(_members || []),
						intelligent_mix_list: [],
					})
				}
			}
		}
	},
	msgHandle: (source: MixCometd) => {
		const { renderPreMix } = get()
		if (!(source.state === 0)) {
			set({ custom_mix_list: [], intelligent_mix_list: [] })
		}
		renderPreMix(source)
	},
	render: (_data) => {
		const { addList, mode, custom_mix_list, removeLi, changeMix } = get()
		const mixMode = useMccStore.getState().mixMode
		// 1.判断当前是否开启混音 2.判断开启混音的类型
		if (mixMode === 0) {
			/**如果没有开启混音 直接添加到定制混音列表 */
			set({ mode: 2 })
			addList(_data)
		} else {
			//开启了混音
			if (mode === 1) {
				//开启智能混音
			} else {
				//开启定制混音   1.add  2.changMix
				const row = _data[0]
				const flag = custom_mix_list.findIndex((item) => {
					return item.mtKey === row.mt_key
				})
				if (flag === -1) {
					addList(_data)
				} else {
					const speaker = useManagerStore.getState().speaker
					if (row?.mt_key === speaker?.mtKey) {
						//发言方不能移除定制混音列表
						Alert(t('发言人必须参加混音'))
						return
					}
					removeLi([row.mt_key])
				}
				if (row.isMt || row.speaker || row.chairman) {
					changeMix()
				}
			}
		}
	},
	toggleClick: (mtKey) => {
		const { custom_mix_list: list } = get()
		list.forEach((item) => {
			if (item.mtKey === mtKey) {
				item.status.checked = true
			} else {
				item.status.checked = false
			}
		})
		set({ custom_mix_list: [...list], _start: mtKey, _changes: [] })
	},
	toggleCtrl: (mtKey) => {
		const { custom_mix_list: list } = get()
		list.forEach((item) => {
			if (item.mtKey === mtKey) {
				item.status.checked = !item.status.checked
			}
		})
		set({ custom_mix_list: [...list], _start: mtKey, _changes: [] })
	},
	toggleShift: (mtKey) => {
		const { custom_mix_list: list, _changes, _start } = get()
		if (_changes.length > 0) {
			for (const item of list) {
				if (_changes.includes(item.mtKey)) {
					item.status.checked = false
				}
			}
		}
		let newChanges = []
		let startItem = list.find((x) => x.mtKey === _start)
		if (startItem) {
			if (startItem?.mtKey === mtKey) {
				startItem.status.checked = true
				newChanges.push(startItem?.mtKey)
			} else {
				let _flag = false,
					_time = 0
				for (const item of list) {
					if (item.mtKey === mtKey || item.mtKey === _start) {
						item.status.checked = true
						newChanges.push(item.mtKey)
						_flag = ++_time === 1
					}
					if (_flag) {
						item.status.checked = true
						newChanges.push(item.mtKey)
					}
				}
			}
		}
		set({ custom_mix_list: [...list], _changes: newChanges })
	},
}))
export const useMixStore = create(store)
